//
//  StringHelper.m
//

#import "StringHelper.h"
#import "GTMBase64.h"
#import <CommonCrypto/CommonDigest.h>

@implementation StringHelper

+ (BOOL)stringIsEmpty:(NSString *)str {
    BOOL ret = NO;
    if (str == nil) {
        ret = YES;
    } else {
        NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([temp length] < 1) {
            ret = YES;
        }
    }
    return ret;
}

+ (NSString *)stringOrEmpty:(NSString *)str {
    return (str == nil ? @"" : str);
}

+ (NSUInteger)chineseStringLen:(NSString *)str {
    int newLength = 0;
    if (str != nil) {
        int i = 0;
        for (i = 0; i < [str length]; ++i) {
            unichar c = [str characterAtIndex:i];
            if (isalnum(c) || ' ' == c) {
                newLength += 1;
            } else {
                newLength += 2;
            }
        }
    }
    return newLength;
}

+ (NSString *)cutString:(NSString *)str length:(NSUInteger)length {
    NSString *ret = str;
    if (str != nil) {
        assert(length > 0);
        //const int twiceLength=length*2;
        int newLength = 0;
        int i = 0;
        int lastIndex = 0;
        for (i = 0; i < length && i < [str length]; ++i) {
            unichar c = [str characterAtIndex:i];
            if (isalnum(c) || ' ' == c) {
                //英文算半个
                if (newLength + 1 <= length) {
                    newLength += 1;
                } else {
                    break;
                }
            } else {
                if (newLength + 2 <= length) {
                    newLength += 2;
                } else {
                    break;
                }
            }
            ++lastIndex;
        }
        ret = [str substringToIndex:lastIndex];
        assert(ret != nil);
    }
    return ret;
}

+ (NSString *)MD5:(NSString *)str {
    if ([str length] == 0) {
        return nil;
    }
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];

    CC_MD5(cStr, strlen(cStr), result);

    return [[NSString
        stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                         result[0], result[1],
                         result[2], result[3],
                         result[4], result[5],
                         result[6], result[7],
                         result[8], result[9],
                         result[10], result[11],
                         result[12], result[13],
                         result[14], result[15]] lowercaseString];
}

+ (NSString *)encodeBase64:(NSString *)str {
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    //转换到base64
    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return [base64String autorelease];
}

+ (NSString *)decodeBase64:(NSString *)str {
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    //base64解码
    data = [GTMBase64 decodeData:data];
    NSString *retString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return [retString autorelease];
}

+ (NSString *)generateGUID {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

+ (NSString *)stringByDecodingURLFormat:(NSString *)str {
    NSString *result = [str stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

+ (NSString *)stringByEncodingURLFormat:(NSString *)str {
    NSString *resultStr = str;

    CFStringRef originalString = (CFStringRef)str;
    CFStringRef leaveUnescaped = CFSTR(" ");
    CFStringRef forceEscaped = CFSTR("!*'();:@&=+$,/?%#[]");

    CFStringRef escapedStr;
    escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                         originalString,
                                                         leaveUnescaped,
                                                         forceEscaped,
                                                         kCFStringEncodingUTF8);

    if (escapedStr) {
        NSMutableString *mutableStr = [NSMutableString stringWithString:(NSString *)escapedStr];
        CFRelease(escapedStr);

        // replace spaces with plusses
        [mutableStr replaceOccurrencesOfString:@" "
                                    withString:@"%20"
                                       options:0
                                         range:NSMakeRange(0, [mutableStr length])];
        resultStr = mutableStr;
    }
    return resultStr;
}

+ (NSString *)encodeGB2312Str:(NSString *)str {
    CFStringRef nonAlphaNumValidChars = CFSTR("![        DISCUZ_CODE_1        ]’()*+,-./:;=?@_~");
    NSString *preprocessedString = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)str, CFSTR(""), kCFStringEncodingGB_18030_2000);
    NSString *newStr = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)preprocessedString, NULL, nonAlphaNumValidChars, kCFStringEncodingGB_18030_2000) autorelease];
    [preprocessedString release];
    return newStr;
}

+ (NSString *)decodeGB2312Str:(NSString *)str {
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *retStr = [str stringByReplacingPercentEscapesUsingEncoding:enc];
    return retStr;
}

+ (BOOL)versionCompare:(NSString *)localVersion serverVersion:(NSString *)serverVersion {
    return [localVersion compare:serverVersion options:NSNumericSearch] != NSOrderedAscending;
}

+ (BOOL)compareString:(NSString *)oneString isEqualTo:(NSString *)anotherString {
    //判断逻辑是两个变量如果只有一个为nil，则为不同，随后比较他们的值，如果不同返回假
    if ((nil == oneString && nil == anotherString) || (nil != oneString && nil != anotherString && [oneString isEqualToString:anotherString])) {
        return YES;
    }
    return NO;
}

+ (NSString *)sqliteEscape:(NSString *)keyWord {
    keyWord = [keyWord stringByReplacingOccurrencesOfString:@"'" withString:@"''"];

    return keyWord;
}

+ (BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+(BOOL)isValidChinesePhone:(NSString *)number{
    NSString *phoneRegex = @"1[0-9]{10}";
    NSPredicate *phoneCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",phoneRegex];
    return [phoneCheck evaluateWithObject:number];
}

+ (BOOL)isOnlyNumOrCharacter:(NSString *)string{
    NSString *characterFormat = @"^[A-Za-z]+$";
    NSString *numberFormat = @"^[0-9]+$";
    NSPredicate *characterCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", characterFormat];
    NSPredicate *numberCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", numberFormat];
    
    if ([characterCheck evaluateWithObject:string]) {
        return YES;
    } else if ([numberCheck evaluateWithObject:string]) {
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)isChineseCharacter:(NSString *)string {
    BOOL isChinese = NO;
    NSString *chineseFormat = @"^[\u4e00-\u9fa5]+$";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",chineseFormat];
    for (int i = 0; i < [string length]; i ++) {
        NSString *str = [string substringWithRange:NSMakeRange(i, 1)];
        if (str && [pre evaluateWithObject:str]) {
            isChinese = YES;
            break;
        }
    }
    return isChinese;
}

+ (BOOL)isValidateMIEPassword:(NSString *)password {
    // length >8, can't only character or only numbers
    NSString *characterFormat = @"^[A-Za-z]+$";
    NSString *numberFormat = @"^[0-9]+$";
    NSPredicate *characterCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", characterFormat];
    NSPredicate *numberCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", numberFormat];

    if ([password length] < 8||[password length]>16) {
        return NO;
    } else if ([characterCheck evaluateWithObject:password]) {
        return NO;
    } else if ([numberCheck evaluateWithObject:password]) {
        return NO;
    } else {
        return YES;
    }
}

+ (NSString *)formatDistanceFromNumber:(NSNumber *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"###,###,##0.00";
//    formatter.roundingMode = NSNumberFormatterRoundFloor;
    NSString *result = [formatter stringFromNumber:number];
    [formatter release];
    return result;
}

+ (NSString *)formattedStringFromNumber:(NSNumber *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"###,###,##0.0";
//    formatter.roundingMode = NSNumberFormatterRoundFloor;
    NSString *result = [formatter stringFromNumber:number];
    [formatter release];
    return result;
}

+ (NSString *)formatCalFromNumber:(NSNumber *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"###,###,###";
    //    formatter.roundingMode = NSNumberFormatterRoundFloor;
    NSString *result = [formatter stringFromNumber:number];
    [formatter release];
    return result;
}

+ (NSString *)ceilingToOneFraction:(NSNumber *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"0.00";
    formatter.roundingMode = NSNumberFormatterRoundCeiling;
    NSString *result = [formatter stringFromNumber:number];
    [formatter release];
    return result;
}

+ (NSNumber *)valueFromString:(NSString *)string{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"###,###,##0.0";
    formatter.roundingMode = NSNumberFormatterRoundFloor;
    NSNumber *num = [formatter numberFromString:string];
    [formatter release];
    return num;
}

+ (NSString *)commaNumber:(NSNumber *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *result = [formatter stringFromNumber:number];
    [formatter release];
    return result;
}

+ (NSString *)noStyleNumber:(NSNumber *)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterNoStyle;
    NSString *result = [formatter stringFromNumber:number];
    [formatter release];
    return result;
}

+ (NSString *)currentLanguage{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    return preferredLang;
}

+ (int)minutesFromSec:(int)sec{
    int result = 0;
    if (sec < 60) {
        result = sec > 0 ? 1 : sec;
    }else{
        if (sec % 60 >= 30) {
            result = sec / 60 + 1;
        }else{
            result = sec / 60;
        }
    }
    return result;
}

//get height base on font and content
+(CGFloat)HeightWithBoundSize:(CGSize)size Text:(NSString*)text font:(UIFont *)font{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    NSRange allRange = [text rangeOfString:text];
    [attrStr addAttribute:NSFontAttributeName
                    value:font
                    range:allRange];
    
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&allRange];
    CGRect labelFrame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
    CGFloat height =labelFrame.size.height;
    [attrStr release];
    return height;
}

+ (BOOL)isContainerOfString:(NSString *)string withCompareString:(NSString *)compareString
{
    BOOL isContainer = NO;
    
    NSRange range = [string rangeOfString:compareString];
    
    if (range.length > 0)
    {
        isContainer = YES;
    }
    
    return isContainer;
}

@end

@implementation NSString (StringHelper)

- (BOOL)compareMacAddrSuffixIsEqual:(NSString *)macAddr {
    if (nil == macAddr) {
        return NO;
    }

    if (0 == self.length || 0 == macAddr.length || self.length != macAddr.length) {
        return NO;
    }

    NSString *mySubString = [self substringFromIndex:1];
    NSString *macSubString = [macAddr substringFromIndex:1];
    return [mySubString isEqualToString:macSubString];
}

@end